//
//  AppDelegate+SDK.m
//  DCProject
//
//  Created by bigbing on 2019/3/30.
//  Copyright © 2019 bigbing. All rights reserved.
//

#import "AppDelegate+SDK.h"
#import <WXApi.h>


@implementation AppDelegate (SDK)

#pragma mark - 初始化三方SDK
- (void)initSDKWithOptions:(NSDictionary *)launchOptions{
    
//    [self initAppearance];
//    [self confitUShareSettings];
//    [self configUSharePlatfcorms];
//    [self configUconfigure];
//    [self initBugly];
    [self initJPushWithOptions:launchOptions];
//    [self addActivity];
//    [self setSVProgressHUDInfo];
//    [self initMeiQia];
//    [self initWXApi];
//    [self initShanYan];
//    [self initMaMap];
    
//    // 注册通知  监听自定义消息
//    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
//    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
//
//    NSDictionary * remoteNotification =  [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
//    if (remoteNotification) {
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//               [self responseEventNotiction:remoteNotification];
//        });
//    }
    
}


#pragma mark - 微信
- (void)initWXApi{
//    NSLog(@"===WXApi:%@",[WXApi getApiVersion]);
      [WXApi registerApp:DCWX_AppKey universalLink:DCWX_UniversalLinks];
//    [WXApi startLogByLevel:WXLogLevelNormal logBlock:^(NSString *log) {
//        NSLog(@"WXApilog : %@", log);
//    }];
    
//    [WXApi checkUniversalLinkReady:^(WXULCheckStep step, WXCheckULStepResult* result) {
//        NSLog(@"WeixinSDK2：%@, %u, %@, %@", @(step), result.success, result.errorInfo, result.suggestion);
//    }];
}


#pragma mark - 美洽
- (void)initMeiQia{
//    [MQManager initWithAppkey:DCMeiQia_AppKey completion:^(NSString *clientId, NSError *error) {
//        if (!error) {
//            NSLog(@"美洽 SDK：初始化成功:%@",[MQManager getCurrentClientInfo]);
//        } else {
//            NSLog(@"error:%@",error);
//        }
//    }];
}

#pragma mark - 高德地图
- (void)initMaMap{
//    [AMapServices sharedServices].apiKey = DCAmap_AppKey;
}

#pragma mark - 闪验
/// 闪验
-(void)initShanYan{
//    [CLShanYanSDKManager initWithAppId:DCShanYanKey complete:^(CLCompleteResult * _Nonnull completeResult) {
//        NSLog(@"==completeResult:%@,%@",completeResult.message,completeResult.data);
//    }];
}



#pragma mark - 设置SVProgressHUD参数
- (void)setSVProgressHUDInfo{
//    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
//    [SVProgressHUD setFont:[UIFont fontWithName:PFR size:15]];
//    [SVProgressHUD setForegroundColor:[UIColor dc_colorWithHexString:DC_333333]];
//    [SVProgressHUD setMinimumDismissTimeInterval:2];
//    [SVProgressHUD setMaximumDismissTimeInterval:2];
//

}


#pragma mark - 显示网络请求时顶部小圆圈
- (void)addActivity
{
//    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
}


#pragma mark - Bugly初始化
- (void)initBugly{
//    BuglyConfig * config = [[BuglyConfig alloc] init];
//    //#if DEBUG
//    config.debugMode = YES;
//    //#endif
//    config.blockMonitorEnable = YES;
//    config.blockMonitorTimeout = 1.5;
//    config.channel = @"AppStore";
//    config.version = APP_VERSION;
//    config.deviceIdentifier = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
//    config.delegate = self;
//    config.consolelogEnable = YES;
//    config.viewControllerTrackingEnable = YES;
//    config.reportLogLevel = BuglyLogLevelWarn;
//
//    [Bugly startWithAppId:DCBugly_AppiD config:config];
}


#pragma mark - 友盟
- (void)confitUShareSettings
{
//    /*
//     * 打开图片水印
//     */
//    [UMSocialGlobal shareInstance].isUsingWaterMark = YES;
//    /*
//     * 关闭强制验证https，可允许http图片分享，但需要在info.plist设置安全域名
//     <key>NSAppTransportSecurity</key>
//     <dict>
//     <key>NSAllowsArbitraryLoads</key>
//     <true/>
//     </dict>
//     */
//    [UMSocialGlobal shareInstance].isUsingHttpsWhenShareContent = NO;
}


#pragma mark - 初始化友盟统计
- (void)configUconfigure
{
    // 友盟统计
//    [UMConfigure initWithAppkey:DCUM_AppKey channel:@"App Store"];
}


#pragma mark - 初始化友盟分享
- (void)configUSharePlatfcorms
{
//    [[UMSocialManager defaultManager] openLog:YES];
//
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession|UMSocialPlatformType_WechatTimeLine appKey:DCWX_AppKey appSecret:DCWX_AppSecret redirectURL:@"http://mobile.umeng.com/social"];
//    /*
//     * 移除相应平台的分享，如微信收藏
//     */
//    [[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite)]];
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:DCQQ_AppKey /*设置QQ平台的appID*/  appSecret:DCQQ_AppSecret redirectURL:@"http://mobile.umeng.com/social"];
//    //微信和QQ完整版会校验合法的universalLink，不设置会在初始化平台失败
//    [UMSocialGlobal shareInstance].universalLinkDic = @{@(UMSocialPlatformType_WechatSession):@"https://www.yqfzwang.com/app",@(UMSocialPlatformType_WechatTimeLine):@"https://www.yqfzwang.com/app",@(UMSocialPlatformType_QQ):@"https://www.yqfzwang.com/app/qq_conn/101830605",@(UMSocialPlatformType_Qzone):@"https://www.yqfzwang.com/app/qq_conn/101830605"};
    
    
    
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:DCSina_AppKey  appSecret:DCSina_AppSecret redirectURL:@"http://mobile.umeng.com/social"];
    // 自定义ui面板
//    [UMSocialUIManager addCustomPlatformWithoutFilted:UMSocialPlatformType_WechatSession withPlatformIcon:[UIImage imageNamed:@"vx-1"] withPlatformName:@"微信"];
//    [UMSocialUIManager addCustomPlatformWithoutFilted:UMSocialPlatformType_WechatTimeLine withPlatformIcon:[UIImage imageNamed:@"pengyouq"] withPlatformName:@"朋友圈"];
////    [UMSocialUIManager addCustomPlatformWithoutFilted:UMSocialPlatformType_Sina withPlatformIcon:[UIImage imageNamed:@"zt_wb"] withPlatformName:@"微博"];
//    [UMSocialUIManager addCustomPlatformWithoutFilted:UMSocialPlatformType_Qzone withPlatformIcon:[UIImage imageNamed:@"kongjian"] withPlatformName:@"QQ空间"];
//    [UMSocialUIManager addCustomPlatformWithoutFilted:UMSocialPlatformType_QQ withPlatformIcon:[UIImage imageNamed:@"qq"] withPlatformName:@"QQ"];
    
}


//// 支持所有iOS系统
//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
//{
////    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
////    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
////    if (!result) {
////
////        NSLog(@"url1 -- %@",url.absoluteString);
////
////        // 支付宝支付
////        if ([url.host isEqualToString:@"safepay"]) {
////            //跳转支付宝钱包进行支付，处理支付结果
////            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
////                NSLog(@"result = %@",resultDic);
////                [[NSNotificationCenter defaultCenter]postNotificationName:DC_NotificationName_Alipay object:self userInfo:resultDic];
////            }];
////            return YES;
////        }
////
////        // 微信支付回调
////        return [WXApi handleOpenURL:url delegate:self];
////    }
////    return result;
//    
//    return YES;
//}


#pragma mark - 初始化极光推送
- (void)initJPushWithOptions:(NSDictionary *)launchOptions
{

}


#pragma mark - <JPUSHRegisterDelegate>

//
//
//#pragma mark- JPUSHRegisterDelegate
//// iOS 12 Support
//- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{
//    if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
//        //从通知界面直接进入应用
//    }else{
//        //从通知设置界面进入应用
//    }
//}
//
//// iOS 10 Support
//- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
//    // Required
//    NSDictionary * userInfo = notification.request.content.userInfo;
//    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
//        [JPUSHService handleRemoteNotification:userInfo];
//    } else {
//        // 本地通知
//    }
//    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
//}
//
//// iOS 10 Support
//- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
//    // Required
//    NSDictionary *userInfo = response.notification.request.content.userInfo;
//    [PushMessageUtil sharedManager].dictPushInfo = [userInfo copy];
//    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
//      [JPUSHService handleRemoteNotification:userInfo];
//    }
//    completionHandler();// 系统要求执行这个方法
//}
//
//
//- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
//
//    // Required, iOS 7 Support
//    [JPUSHService handleRemoteNotification:userInfo];
//    completionHandler(UIBackgroundFetchResultNewData);
//}
//
//- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
//
//    // Required,For systems with less than or equal to iOS6
//    [JPUSHService handleRemoteNotification:userInfo];
//}


#pragma mark - 监听到通知
- (void)networkDidReceiveMessage:(NSNotification *)sender
{
    NSDictionary * dictionary = sender.userInfo;
    NSLog(@"获取到通知 - %@",dictionary);
}


#pragma mark - 通知处理
- (void)responseEventNotiction:(NSDictionary *)dict
{
    //    {
    //        "_j_msgid" : 38280607701293106,
    //        "_j_business" : 1,
    //        "_j_uid" : 26413570807,
    //        "id" : 16,
    //        "aps" : {
    //            "alert" : "测评",
    //            "badge" : 1,
    //            "sound" : "happy"
    //        },
    //        "title" : "测评",
    //        "type" : 2,
    //        "detailType" : 2,
    //        "url" : "http:\/\/47.111.23.72:8058\/qingyang_web\/web\/class\/details.html?id=16"
    //    }
    
//    [[NSNotificationCenter defaultCenter] postNotificationName:DC_JPush_NotificationName object:self userInfo:dict];
}



#pragma mark - <BuglyDelegate>
//- (NSString * BLY_NULLABLE)attachmentForException:(NSException * BLY_NULLABLE)exception{
//    NSLog(@"(%@:%d) %s %@",[[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, __PRETTY_FUNCTION__,exception);
//    return @"This is an attachment";
//}

#pragma mark - 支付宝支付处理逻辑 ios9.0之后版本
//- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
//{
////    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url options:options];
////    if (!result) {
////        // 其他如支付等SDK的回调
////        NSLog(@"url2 -- %@",url.absoluteString);
////        if ([url.host isEqualToString:@"safepay"]) {  // 跳转支付宝钱包进行支付，处理支付结果
////            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
////                NSLog(@"支付宝支付结果 = %@",resultDic);
////                [[NSNotificationCenter defaultCenter]postNotificationName:DC_NotificationName_Alipay object:self userInfo:resultDic];
////            }];
////            return YES;
////        }else if ([url.host isEqualToString:@"oauth"] || [url.host isEqualToString:@"pay"] || [url.host isEqualToString:@"wapoauth"]){
////            //微信登录/支付
////            return [WXApi handleOpenURL:url delegate:self];
////        }
////    }
////    return result;
//    return YES;
//}
//- (BOOL)application:(UIApplication *)application
//  continueUserActivity:(NSUserActivity *)userActivity
//   restorationHandler:(nonnull void (^)  (NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler{
//    return [WXApi handleOpenUniversalLink:userActivity
//                             delegate:self];
//}
//
//#pragma mark - 重写微信回调
//- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
//    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
//    if (!result) {
//        // 微信支付回调
//        return [WXApi handleOpenURL:url delegate:self];
//
//    }
//    return  result;
//}
//
//-(void)application:(UIApplication *)application handleIntent:(INIntent *)intent completionHandler:(void (^)(INIntentResponse * _Nonnull))completionHandler{
//    NSLog(@"handleIntent");
//}

#pragma mark - 微信回调
//- (void)onResp:(BaseResp *)resp{
//    if ([resp isKindOfClass:[PayResp class]]) {
//        PayResp * response = (PayResp *)resp;
//
//        NSDictionary * dict = [response mj_JSONObject];
//        [[NSNotificationCenter defaultCenter] postNotificationName:DC_NotificationName_Wechat object:self userInfo:dict];
//        NSLog(@"微信支付结果 - %@",dict);
//    }
//
////    // 向微信请求授权后,得到响应结果
////    if ([resp isKindOfClass:[SendAuthResp class]]) {
////        SendAuthResp *temp = (SendAuthResp *)resp;
////
////        if([temp.state isEqualToString:@"wx_oauth_authorization_state"]){//微信授权成功
////            NSString * code = temp.code; //获得code
////            [[NSNotificationCenter defaultCenter] postNotificationName:@"WXLoginCode" object:self userInfo:@{@"code":code}];
////        }
////    }
//}


#pragma mark --- 配置框架结构
- (void)initAppearance
{
    //设置UINavigationBar样式
    [UINavigationBar appearance].barTintColor = [UIColor whiteColor];//设置NavBar背景色
    [UINavigationBar appearance].tintColor = [UIColor dc_colorWithHexString:DC_333333];//设置NavBar文字颜色
    [UINavigationBar appearance].titleTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor dc_colorWithHexString:DC_333333],NSForegroundColorAttributeName,[UIFont systemFontOfSize:16 weight:UIFontWeightMedium],NSFontAttributeName, nil];
    [UINavigationBar appearance].shadowImage = [[UIImage alloc]init];
    [[UINavigationBar appearance] setTranslucent:NO];
    
    if (@available(iOS 15.0, *)){
        UINavigationBarAppearance *apperance=[[UINavigationBarAppearance alloc]init];
        apperance.backgroundColor = [UIColor whiteColor];//设置背景色
        [apperance setTitleTextAttributes:@{
            NSFontAttributeName:[UIFont systemFontOfSize:16 weight:UIFontWeightMedium],NSForegroundColorAttributeName:[UIColor dc_colorWithHexString:DC_333333]}];//设置标题字体
        apperance.shadowImage = [[UIImage alloc]init];
        apperance.shadowColor = [UIColor clearColor];//分割线去除
        [UINavigationBar appearance].standardAppearance = apperance;
        [UINavigationBar appearance].scrollEdgeAppearance = [UINavigationBar appearance].standardAppearance;//重新赋值
    }
    
    
    if (@available(ios 11.0,*)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    // 设置tableviewcell线条颜色
    if (@available(iOS 15.0, *)) {
        [UITableView appearance].sectionHeaderTopPadding = 0;
    }
    [UITableView appearance].estimatedRowHeight = 0;
    [UITableView appearance].estimatedSectionFooterHeight = 0;
    [UITableView appearance].estimatedSectionHeaderHeight = 0;
    [UITableView appearance].separatorColor = [UIColor dc_colorWithHexString:DC_EEEEEE];
    [UITableView appearance].tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, CGFLOAT_MIN)];
    [UITableView appearance].tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, CGFLOAT_MIN)];
    
//    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD setFont:[UIFont fontWithName:PFR size:15]];
//    [SVProgressHUD setForegroundColor:[UIColor dc_colorWithHexString:DC_333333]];
    [SVProgressHUD setMinimumDismissTimeInterval:2];
    [SVProgressHUD setMaximumDismissTimeInterval:2];
    
    [self setupBarButtonItemTheme];
}

/**
 *  设置UIBarButtonItem的主题
 */
-(void)setupBarButtonItemTheme {
    //通过设置 appearance对象，能够修改整个项目中所有UIBarButtonItem的样式
    UIBarButtonItem *appearance = [UIBarButtonItem appearance];
    
    //设置文字的属性
    //1.设置普通状态下文字的属性
    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    //设置字体
    textAttrs[NSFontAttributeName] = [UIFont systemFontOfSize:15.0];
    
    //设置颜色为橙色
    textAttrs[NSForegroundColorAttributeName] = [UIColor dc_colorWithHexString:@"#131217"];
    [appearance setTitleTextAttributes:textAttrs forState:UIControlStateNormal];

    //2.设置高亮状态下文字的属性
    NSMutableDictionary *hightextAttrs = [NSMutableDictionary dictionaryWithDictionary:textAttrs];
    //设置颜色为红色
    hightextAttrs[NSForegroundColorAttributeName] = [UIColor dc_colorWithHexString:@"#131217"];
    [appearance setTitleTextAttributes:hightextAttrs forState:UIControlStateHighlighted];

    //3.设置不可用状态下文字的属性
    NSMutableDictionary *disabletextAttrs = [NSMutableDictionary dictionaryWithDictionary:textAttrs];
    disabletextAttrs[NSForegroundColorAttributeName] = [UIColor dc_colorWithHexString:@"#131217"];
    [appearance setTitleTextAttributes:disabletextAttrs forState:UIControlStateDisabled];
}

-(UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
    if (!color || size.width <= 0 || size.height <= 0) return nil;
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}


@end
